package com.wu.getnumberofk;

/**
 * 数字在升序数组中出现的次数
 *
 * @author lynn
 * @date 2020/8/13 - 12:46
 */
public class Solution {
    public static int GetNumberOfK(int[] array, int k) {
        int l = 0;
        int r = array.length - 1;
        int mid;
        int res = 0;
        while (l <= r) {
            mid = l + (r - l) / 2;
            if (array[mid] == k) {
                res++;
                int i = mid - 1;
                while (i >= 0 && array[i] == k) {
                    i--;
                    res++;
                }
                i = mid + 1;
                while (i < array.length && array[i] == k) {
                    i++;
                    res++;
                }
                break;
            } else if (array[mid] > k) {
                r = mid - 1;
            } else {
                l = mid + 1;
            }
        }
        return res;
    }

    public static void main(String[] args) {
        int[] arr = new int[]{1, 2, 3, 3, 3, 3};
        int i = GetNumberOfK(arr, 3);
        System.out.println(i);
    }
}